package kr.co.insoft.framework.util;

import java.util.Map;

import kr.co.insoft.framework.exceptions.ExceptionCode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Scope("singleton")
public class RestClientUtil<T> {
	private static final Logger logger = LoggerFactory
			.getLogger(RestClientUtil.class);
	RestTemplate restTemplate;

	/**
	 * T 객체로 반환
	 * 
	 * @param url
	 * @param responseType
	 * @param urlVariables
	 * @return
	 */
	public T get(String url, Class<T> responseType, Map<String, ?> urlVariables) {
		try {
			restTemplate = new RestTemplate();
			return restTemplate.getForObject(url, responseType, urlVariables);
		} catch (Exception e) {
			logger.error(ExceptionCode.REST_EXCEPTION, e);
			return null;
		}
	}

	/**
	 * 
	 * @param url
	 * @param requestType
	 *            보내는 객체
	 * @param responseType
	 *            받는 객체
	 * @return
	 */
	public T post(String url, Class<?> requestType, Class<T> responseType) {
		try {
			restTemplate = new RestTemplate();
			return restTemplate.postForObject("url", requestType, responseType);
		} catch (Exception e) {
			logger.error(ExceptionCode.REST_EXCEPTION, e);
			return null;
		}
	}

	/**
	 * json 문자열로 변환하여 반환한다.
	 * 
	 * @param url
	 * @param urlVariables
	 * @return
	 */
	public String get(String url, Map<String, ?> urlVariables) {
		try {
			return (new RestTemplate()).getForObject(url, String.class, urlVariables);
//			JSONSerializer jsonSerializer = new JSONSerializer();
//			return jsonSerializer
//					.transform(new NullExcludeTransformer(), void.class)
//					.exclude("*.class")
//					.deepSerialize(
//							restTemplate.getForObject(url, String.class, urlVariables));
		} catch (Exception e) {
			logger.error(ExceptionCode.REST_EXCEPTION, e);
			return null;
		}
	}
}
